Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    title:{
      type: String,
      value: '请选择',
    },
    show:{
      type: Boolean,
      value: false,
    },
    multi:{
      type: Boolean,
      value: false,
    },
    textfield:{
      type: String,
      value: "name",
    },
    valuefield:{
      type: String,
      value: "id",
    },
    list: {
      type: Array,
      value: []
    }
  },
  data:{
    searchText:'',
    selectCount:0,
    result:[]
  },
  observers:{
    'list':function(data){
      this.initData();
    },
  },
  attached: function attached() {
    this.setData({
      search: this.search.bind(this),
    });
  },
  methods:{
    // 初始化数据
    initData(){
      this.setData({
        searchText:'',
        selectCount:0,
      });
      var list = this.properties.list;
      var result = new Array();
      for(var i =0; i < list.length;i++){
        var obj = list[i];
        var item = {
          id:obj[this.properties.valuefield],
          name:obj[this.properties.textfield],
          checked:false,
        };
        result.push(item);
      }
      this.setData({
        result:result,
      });
    },
    // 筛选数据
    filterData(text){
      var list = this.properties.list;
      var result = new Array();
      for(var i =0; i < list.length;i++){
        var obj = list[i];
        var item = {
          id:obj[this.properties.valuefield],
          name:obj[this.properties.textfield],
        };
        if(!!text){
          // 判断是包含输入的字符串
          if(item.name.indexOf(text) < 0){
            continue;
          }
        }
        result.push(item);
      }
      this.setData({
        result:result,
      });
    },
    // 输入搜素文本
    search:function(value){
      this.filterData(value);

      return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([])
        }, 200)
      })
    },
    // 清空搜索文本
    searchClear(e){
      this.filterData();
    },
    // 选中
    checkedChange(e){
      if(this.data.multi){
        this.setData({
          selectCount:e.detail.value.length,
        });
      } else {
        this.setData({
          selectCount:1,
        });
      }
      this.setData({
        selectedValue:e.detail.value,
      });
      this.triggerEvent("change",{value:e.detail.value});
    },
    // 确认选中
    confirm(e){
      var _this = this;
      if(_this.data.selectCount == 0){
        return;
      }
      _this.triggerEvent("confirm",{value:_this.data.selectedValue});
      this.initData();
    },
    // 组件关闭
    bindClosed(e){
      this.triggerEvent("close");
      this.initData();
    }
  }
})
